package com.uyaer.magic.tick
{
	import com.uyaer.magic.utils.HashMap;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class TimerManager
	{
		private static var timersMap:HashMap = new HashMap();
		private static var _maxCount:int = 0;
		private static var _totalCount:int = 0;
		/**
		 *添加一个无限循环处理的回调，记得主动移除 
		 * @param callback 每一tick回调
		 * @param delay 毫秒数
		 * 
		 */		
		public static function addLoop(callback:Function,delay:int):void{
			if(timersMap.hasKey(callback)){
				throw "TimerManager::addLoop() timer not stop?";
				return;
			}
			var timer:UTimer = TimerPool.getOne(delay,0);
			if(timer.hasEventListener(TimerEvent.TIMER)){
				throw "about clear all listener?";
			}
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			timersMap.put(callback,timer);
			timer.start();
			callback && callback();
			
			_totalCount++;
			_maxCount = Math.max(_maxCount , timerCount);
			
			function onTimer(e:TimerEvent):void{
				callback && callback();
			}
		}
		
		/**
		 *移除无限循环 
		 * @param callback
		 * 
		 */		
		public static function removeLoop(callback:Function):void{
			if(timersMap.hasKey(callback)){
				var timer:UTimer = timersMap.get(callback);
				TimerPool.recycle(timer);
				timersMap.remove(callback);
			}
		}
		
		/**
		 *添加延时处理回调 
		 * @param callback
		 * @param delay
		 * 
		 */		
		public static function addDelay(callback:Function,delay:int):void{
			var timer:UTimer = TimerPool.getOne(delay,1);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE,removeMe);
			timersMap.put(callback,timer);
			timer.start();
			
			_totalCount++;
			_maxCount = Math.max(_maxCount , timerCount);
			
			function removeMe(e:TimerEvent):void{
				TimerPool.recycle(timer);
				callback && callback();
			}
		}
		
		//============   用于性能统计   ============//
		
		/**
		 *所有timer数量 
		 * @return 
		 * 
		 */		
		public static function get timerCount():int{
			return timersMap.getKeys().length;
		}
		
		/**
		 *获得最大同时存在的timer数量 
		 * @return 
		 * 
		 */		
		public static function get maxCount():int{
			return _maxCount;
		}
		
		/**
		 *获得累计存在数量 
		 * @return 
		 * 
		 */		
		public static function get totalCount():int{
			return _totalCount;
		}
		
		/**
		 *获得delay毫秒数以下的同时存在的timer 
		 * @param delay
		 * @return 
		 * 
		 */		
		public static function getLoopCount(delay:int = 500):int{
			var arr:Array = timersMap.getValues();
			var count:int = 0;
			for each (var timer:UTimer in arr){
				if(timer.delay<delay){
					count ++;
				}
			}
			return count;
		}
		
		
	}
}